using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FiltronASP.Logger;

namespace FiltronASP.Models.DAO.WIX
{
    public class WixEngineDAO : Abstracts.AbstractGenericDAO<WixEngine, System.Nullable<int>>,
       Interfaces.WIX.IWixEngineDAO
    {
        /// <summary>
        /// Metoda zwracajaca nazwe parametru bedacego kluczem glownym tabeli.
        /// </summary>
        /// <returns>nazwa klucza glownego</returns>
        protected override string GetKeyProperty()
        {
            return "engine_id";
        }

        /// <summary>
        /// Pobieranie obiektow na podstawie modelu.
        /// </summary>
        /// <param name="modelId">model samochodu</param>
        /// <returns>rekordy o zadanym modelu lub null, gdy nie ma</returns>
        public IQueryable<WixEngine> FindByModel(int modelId)
        {
            if (modelId.Equals(0))
            {
                return null;
            }   //if
            try
            {
                IQueryable<WixEngine> engines = this._cmsEntitiesDataContext.WixEngines.Where(
                    engi => this._cmsEntitiesDataContext.WixEngineModels.Where( enmo => 
                        enmo.model_id.Equals(modelId)).Select(em => em.engine_id).Contains(engi.engine_id)
                        );
                if (!(engines.Any()))
                {
                    return null;
                }   //if
                return engines;
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
            }   //catch
            return null;
        }

        /// <summary>
        /// Pobieranie obiektow na podstawie modelu i roku.
        /// </summary>
        /// <param name="modelId">model samochodu</param>
        /// <param name="year">rok produkcji</param>
        /// <returns>rekordy o zadanym modelu lub null, gdy nie ma</returns>
        public IQueryable<WixEngine> FindByModelAndYear(int modelId, int year)
        {
            if (modelId.Equals(0) || year.Equals(0))
            {
                return null;
            }   //if
            try
            {
                IQueryable<WixEngine> engines = this._cmsEntitiesDataContext.WixEngines.Where(
                    engi => (engi.engine_year_from <= year) && (engi.engine_year_to >= year) && this._cmsEntitiesDataContext.WixEngineModels.Where(enmo =>
                        enmo.model_id.Equals(modelId)).Select(em => em.engine_id).Contains(engi.engine_id)
                        );
                if (!(engines.Any()))
                {
                    return null;
                }   //if
                return engines;
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
            }   //catch
            return null;
        }
    }
}
